<?php

namespace App\Command;

use App\Config\Db;
use Faker\Factory;
use Faker\Provider\zh_CN\Address;
use Noodlehaus\Config;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class CreateOrderTmcCommand extends BaseCommand
{

    private $post;
    private $presell;
    private $is_part = false;
    private $part_sku = [];


    protected function configure()
    {
        $this
            // the name of the command (the part after "bin/console")
            // 命令的名字（"bin/console" 后面的部分）
            ->setName('app:create-order-tmc')
            // the short description shown while running "php bin/console list"
            // 运行 "php bin/console list" 时的简短描述
            ->setDescription('创建tmc订单')
            // the full command description shown when running the command with
            // the "--help" option
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("创建tmc订单") // configure an argument / 配置一个参数
            ->addOption("number", 'num', InputOption::VALUE_REQUIRED, "生成订单数", 1)
            ->addOption("channel_id", 'chid', InputOption::VALUE_REQUIRED, "渠道id", 1)
            ->addOption("post", "", InputOption::VALUE_REQUIRED, "运费", "0.00")
            ->addOption("presell", "", InputOption::VALUE_REQUIRED, "是否预售,1预售，0非预售", 1)
            ->addOption("is_part", '', InputOption::VALUE_OPTIONAL, "指定部分sku、数量转单", "false")
            ->addOption("part_sku", '', InputOption::VALUE_OPTIONAL, '部分sku&个数,例如:[{"sku":"123456","num":1}]', '[]')
            ->addOption("status", 'sts', InputOption::VALUE_REQUIRED, "订单状态", "WAIT_SELLER_SEND_GOODS");
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        date_default_timezone_set("Asia/Shanghai");
        $number     = $input->getOption('number');
        $channel_id = $input->getOption('channel_id');
        $status     = $input->getOption('status');
        $this->presell =  $input->getOption('presell');
        $post = $input->getOption('post');
        $this->post = $post;
        $this->is_part = $input->getOption('is_part');
        $this->part_sku = json_decode($input->getOption('part_sku'),true);
        var_dump($this->part_sku);
        var_dump($input->getOption('part_sku'));

        if($this->is_part =='true' && empty($this->part_sku)){
            echo "部分转单需要正确输入sku数据\n\r";
            die;
            exit(1);
        }


        $helper     = $this->getHelper('question');
        $question   = new ConfirmationQuestion('Whether to push directly into the redis queue?', false);

        $has_push_redis = false;
        if (!$helper->ask($input, $output, $question)) {
            $has_push_redis = false;
        } else {
            $has_push_redis = true;
        }
        $start_time = time();
        $output->writeln("开始时间：" . $start_time);
        $channelData = $this->omsdb->get("t_channel", "*", [
            "channel_id" => $channel_id,
        ]);
        $seller_nick = $channelData['channel_name'];
        //$seller_nick = 'hm官方旗舰店';
        if ($has_push_redis) {
                for ($i = 0; $i < $number; $i++) {
                    if ($i % 1000 == 0) {
                        $mm = memory_get_usage(); //unset()后再查看当前占用内存
                        echo $mm . "\n";
                        unset($this->omsdb);
                        unset($this->tmcdb);
                        unset($this->faker);
                        $this->omsdb = Db::getInstance()->connect_oms();
                        $this->tmcdb = Db::getInstance()->connect_tmc();
                        $this->faker = Factory::create("zh_CN");
                    }
                    $item = $this->create_order($seller_nick, $channel_id, $status);
                    $data = [
                        'type' => 3,
                        'data' => array(
                            'channel_id' => $channel_id,
                            'type'       => 'notify_trade',
                            'status'     => 'TradeCreate',
                            'tid'        => $item['tid'],
                            'response'   => $item['jdp_response'],
                        ),
                    ];
                    $this->do_queue("taobaoorders", "add", $data);
            }
        } else {
            for ($i = 0; $i < $number; $i++) {
                if ($i % 1000 == 0) {
                    gc_collect_cycles();
                    //                    echo  sprintf( '%8d: ', $i ), memory_get_usage(), "\n";
                    $mm = memory_get_usage(); //unset()后再查看当前占用内存
                    echo $mm . "\n";
                    unset($this->omsdb);
                    unset($this->tmcdb);
                    unset($this->faker);
                    $this->omsdb = Db::getInstance()->connect_oms();
                    $this->tmcdb = Db::getInstance()->connect_tmc();
                    $this->faker = Factory::create("zh_CN");
                }
                $this->create_order($seller_nick, $channel_id, $status);
            }
        }

        $end_time = time();
        $output->writeln("结束时间：" . $end_time);
        $output->writeln("耗时时间：" . ($end_time - $start_time));

        $output->writeln([
            'Order Creator',
            '============',
            '',
        ]);

        // outputs a message followed by a "\n"
        $output->writeln('Success!');
    }

    private function create_order($seller_nick, $channel_id, $status)
    {
        $tid = $this->getMillisecond() . mt_rand(100000, 999999);
        //获取创建时间的跨越度，为一天前-至当前的上海时区
        $dt = date('Y-m-d H:i:s');
        //jdp_hashcode哈希码

        $jdp_hashcode = mt_rand(1000000000, 1999999999);
        //随机的类型码
        if ( $this->presell){
            $type = "step";
        }else{
            $type = 'fixed';
        }
//        $type        = $this->faker->randomElement($array = array('fixed', 'step'));
        $name        = $this->faker->name;
        $responeJson = $this->generatedTradeInfo($tid, $dt, $seller_nick, $type, $name, $channel_id, $status);

        $creator = [
            "tid"          => $tid,
            "status"       => $status, //"WAIT_SELLER_SEND_GOODS",//"WAIT_BUYER_PAY",//WAIT_BUYER_CONFIRM_GOODS
            "type"         => $type,
            "seller_nick"  => $seller_nick,
            "buyer_nick"   => $name,
            "created"      => $dt,
            "modified"     => $dt,
            "jdp_created"  => $dt,
            "jdp_modified" => $dt,
            "jdp_hashcode" => $jdp_hashcode,
            "jdp_response" => $responeJson, //$this->faker->realText($maxNbChars = 200, $indexSize = 2)
        ];
        $this->tmcdb->insert("jdp_tb_trade", $creator);
        return $creator;
    }

    private function generatedTradeInfo($tid, $dt, $seller_nick, $type, $name, $channel_id, $status)
    {
        $data = $this->getData();
        if ($this->is_part == "true"){
            $sku_orders = [];
            $skus = $this->config->get("skus");
            foreach ($skus as $sku){
                $sku_orders[$sku['sku_sn']] = $sku;
            }
            $part_orders = [];
            //选出对应的需要退的sku
            foreach($this->part_sku as $item){
                $select_order = $sku_orders[$item['sku']];
                $select_order['num'] = $item['num'];
                $part_orders[] = $select_order;
            }
            $data = $part_orders;
        }
//        var_dump($data);die;
        $this->faker->addProvider(new Address($this->faker));
        $city    = $this->faker->city;
        $respone = [
            "trade_fullinfo_get_response" => [
                "trade" => [
                    "adjust_fee"             => "0.00",
                    "alipay_id"              => 2088802545036797,
                    "alipay_no"              => "2016102521001001795007279709",
                    "alipay_point"           => 0,
                    "available_confirm_fee"  => "1949.00",
                    "buyer_alipay_no"        => "13932626505",
                    "buyer_area"             => "广东省广州市敦和路189号海珠科技园2期1号楼",
                    // 'buyer_message' => $this->config->get("buyer_message"),
                    "buyer_cod_fee"          => "0.00",
                    "buyer_email"            => "",
                    "buyer_nick"             => $name,
                    "buyer_obtain_point_fee" => 0,
                    "buyer_rate"             => false,
                    "cod_fee"                => "0.00",
                    "cod_status"             => "NEW_CREATED",
                    "commission_fee"         => "0.00",
                    "created"                => $dt,
                    "discount_fee"           => "0.00",
                    "has_post_fee"           => true,
                    "is_3D"                  => false,
                    "is_brand_sale"          => false,
                    "is_daixiao"             => false,
                    "is_force_wlb"           => false,
                    "is_lgtype"              => false,
                    "is_part_consign"        => false,
                    "is_wt"                  => false,
                    "modified"               => $dt,
                    "num"                    => 1,
                    "num_iid"                => 544160959115,
                    "orders"                 => [
                        "order" => [
                        ],
                    ],
                    "pay_time"               => $dt,
                    "payment"                => "1949.00",
                    "pcc_af"                 => 0,
                    "pic_path"               => "",
                    "point_fee"              => 0,
                    "post_fee"               => $this->post,
                    "promotion_details"=>[
                        "promotion_detail"=>[
                            ["discount_fee"=>"0.00",
                                "id"=> '126950071993312757',
                                "promotion_desc"=> "聚划算:省0.00元",
                                "promotion_id"=> "Tmall-3153345006_33729171907",
                                "promotion_name"=> "聚划算"]
                        ],
                    ],
                    "price"                  => "1999.00",
                    "real_point_fee"         => 0,
                    "received_payment"       => "0.00",
                    "receiver_address"       => "敦和路189号海珠科技园2期1号楼",
                    "receiver_city"          => "广州市",
                    "receiver_district"      => "海珠区",
                    "receiver_mobile"        => "15102088122",
                    "receiver_name"          => $name,
                    "receiver_state"         => "广东省",
                    "receiver_zip"           => "510900",
                    "seller_alipay_no"       => "fgu@ecco.com",
                    "seller_can_rate"        => false,
                    "seller_cod_fee"         => "0.00",
                    "seller_email"           => "e-commerce-cn@ecco.com",
                    "seller_flag"            => 0,
                    "seller_memo"            => $this->config->get("seller_memo"),
                    "seller_mobile"          => "15921534824",
                    "seller_name"            => $seller_nick,
                    "seller_phone"           => "0571-28181301",
                    "seller_rate"            => false,
                    "service_tags"           => [
                        "logistics_tag" => [
                            [
                                "logistic_service_tag_list" => [
                                    "logistic_service_tag" => [
                                        [
                                            "service_tag"  => "lgType=-4",
                                            "service_type" => "FAST",
                                        ],
                                    ],
                                ],
                                "order_id"                  => $tid,
                            ],
                        ],
                    ],
                    "shipping_type"          => "express",
                    "snapshot_url"           => "l:{$tid}_1",
                    "status"                 => $status,
                    "tid"                    => $tid,
                    "title"                  => $seller_nick,
                    "total_fee"              => "1999.00",
                    "trade_from"             => "WAP,WAP",
                    "type"                   => $type,
                ],
            ],
        ];
        $total_fee = 0;
        $num       = 0;
        foreach ($data as $value) {
            $num += $value['num'];
            $payment = $value['product_price'] * $value['num'];
            $total_fee += $payment;
            $oid = $this->getMillisecond() . mt_rand(1, 99999);
            $order = [
                "adjust_fee"          => "0.00",
                "buyer_rate"          => false,
                "cid"                 => $this->faker->randomNumber(),
                "discount_fee"        => $value['discount'],
                "is_oversold"         => false,
                "num"                 => $value['num'],
                "num_iid"             => $this->faker->randomNumber(),
                "oid"                 => $oid,
                "order_from"          => "WAP,WAP",
                "outer_iid"           => $value['outer_goods_sn'],
                "outer_sku_id"        => $value['sku_sn'],
                "part_mjz_discount"   => "0.00",
                "payment"             => $payment-($value['discount']*$value['num']),
                "pic_path"            => $value['pic_path'],
                "price"               => $value['product_price'],
                "refund_status"       => "NO_REFUND",
                "seller_rate"         => false,
                "seller_type"         => "B",
                "sku_id"              => $value['channel_goods_sn'],
                "sku_properties_name" => $value['goods_name'],
                "snapshot_url"        => "l=>{$tid}_1",
                "status"              => "WAIT_SELLER_SEND_GOODS",
                "title"               => $value['goods_name'],
                "total_fee"           => $payment,
            ];
            $respone['trade_fullinfo_get_response']['trade']['orders']['order'][] = $order;
        }
        $respone['trade_fullinfo_get_response']['trade']['total_fee']             = $total_fee;
        $respone['trade_fullinfo_get_response']['trade']['available_confirm_fee'] = $total_fee;
        $respone['trade_fullinfo_get_response']['trade']['credit_card_fee']       = $total_fee;
        $respone['trade_fullinfo_get_response']['trade']['payment']               = $total_fee;
        $respone['trade_fullinfo_get_response']['trade']['price']                 = $total_fee;
        $respone['trade_fullinfo_get_response']['trade']['num']                   = $num;

        $responeJson = json_encode($respone, JSON_UNESCAPED_UNICODE);
        $respone     = null;
        unset($respone);
        return $responeJson;
    }

}
